package com.hmall.item.controller;

import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.constants.MqConstants;
import com.hmall.item.service.ItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/item")
public class ItemCotroller {

    @Autowired
    private ItemService itemService;

    /**
     *  分页查询数据
     *  PageDTO<Item>
     */
    @GetMapping("/list")
    public PageDTO<Item> getItemByPage(@RequestParam("page") Integer current, @RequestParam("size") Integer pageSize){

        return itemService.getItemByPage(current,pageSize);
    }


    /**
     * 根据id查询商品
     */
    @GetMapping("/{id}")
    public Item getItermById(@PathVariable("id") Long id){
        return itemService.getItermById(id);
    }



    /**
     *  自动注入Springboot封装的RabbitMQ的对象-RabiitTemplate
     */
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 新增商品
     */
    @PostMapping
    public void insertItem(@RequestBody Item item) {
        itemService.insertItem(item);
        // 向RabbitMQ中发送消息
        rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE,MqConstants.ITEM_INSERT_UPDATE_KEY,item.getId());
    }

    /**
     * 商品上架、下架
     */
    @PutMapping("/status/{id}/{status}")
    public void updateStatus(@PathVariable("id") Long id,@PathVariable("status") Integer status){
        itemService.updateStatus(id,status);
        // 向RabbitMQ中发送消息
        rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE,MqConstants.ITEM_INSERT_UPDATE_KEY,id.toString());
    }
    /**
     * 修改商品
     */
    @PutMapping
    public void updateItem(@RequestBody Item item){
        itemService.updateItem(item);
        // 向RabbitMQ中发送消息
        rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE,MqConstants.ITEM_INSERT_UPDATE_KEY,item.getId());
    }
    /**
     * 根据id删除商品
     */
    @DeleteMapping("{id}")
    public void deleteItem(@PathVariable("id") Long id) {
        itemService.removeById(id);
        // 向RabbitMQ中发送消息
        rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE, MqConstants.ITEM_DELETE_KEY,id);
    }









}
